package com.slj.controller;

import com.slj.entity.Products;
import com.slj.service.ProductsService;
import com.slj.uitil.FileUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/products")
@CrossOrigin(origins = "*")
@RequiredArgsConstructor
public class ProductsController {

    @Autowired
    private ProductsService productsService;

    @Autowired
    private FileUtil fileUtil;

    /**
            * 添加商品（带图片上传）
            */
    @PostMapping
    public ResponseEntity<?> addProduct(
            @RequestPart("product") Products product,
            @RequestPart(value = "image", required = false) MultipartFile image) {
        try {
            // 处理图片上传
            if (image != null && !image.isEmpty()) {
                String imagePath = fileUtil.saveFile(image);
                product.setImageUrl("/static/img/" + image.getOriginalFilename());
            }

            int result = productsService.insert(product);
            return result > 0
                    ? ResponseEntity.ok().body("商品添加成功")
                    : ResponseEntity.badRequest().body("商品添加失败");
        } catch (IOException e) {
            return ResponseEntity.internalServerError().body("图片上传失败: " + e.getMessage());
        }
    }

    /**
            * 根据ID获取商品
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getProductById(@PathVariable Integer id) {
        Products product = productsService.selectByPrimaryKey(id);
        return product != null
                ? ResponseEntity.ok(product)
                : ResponseEntity.notFound().build();
    }

    /**
            * 获取所有商品
     */
    @GetMapping
    public ResponseEntity<List<Products>> getAllProducts() {
        List<Products> products = productsService.selectAll();
        return ResponseEntity.ok(products);
    }

    /**
            * 根据名称搜索商品
     */
    @GetMapping("/search")
    public ResponseEntity<List<Products>> searchProductsByName(@RequestParam String name) {
        List<Products> products = productsService.selectByProductName(name);
        return ResponseEntity.ok(products);
    }

    /**
            * 更新商品信息
     */
    @PutMapping
    public ResponseEntity<?> updateProduct(@RequestBody Products product) {
        int result = productsService.updateByPrimaryKey(product);
        return result > 0
                ? ResponseEntity.ok().body("商品更新成功")
                : ResponseEntity.badRequest().body("商品更新失败");
    }

    /**
            * 删除商品
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteProduct(@PathVariable Integer id) {
        int result = productsService.deleteByPrimaryKey(id);
        return result > 0
                ? ResponseEntity.ok().body("商品删除成功")
                : ResponseEntity.badRequest().body("商品删除失败");
    }

    /**
            * 切换商品状态（上架/下架）
            */
    @PostMapping("/{id}/toggle-status")
    public ResponseEntity<?> toggleProductStatus(@PathVariable Integer id) {
        int result = productsService.toggleStatus(id);
        return result > 0
                ? ResponseEntity.ok().body("状态切换成功")
                : ResponseEntity.badRequest().body("状态切换失败");
    }
}